package com.drojian.demo3.multimedia;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.drojian.demo.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class SysCameraActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView mImageView;
    private Button btn1,btn2;
    private Uri photoURI;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.part3_activity_sys_camera);
            initViews();
        }

    private void initViews() {
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        mImageView = findViewById(R.id.image_1);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
    }
    //1.点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn1:
                takePhoto();
                break;
            case R.id.btn2:
                choosePhoto();
                break;
        }
    }

    //2.权限判定
    private void takePhoto() {
            if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    == PackageManager.PERMISSION_GRANTED){
                // 有权限去拍照
                doTake();
            }else{
                //申请权限
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},1);
            }
    }
    //3.接受权限申请结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 1){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                doTake();
            }else {
                Toast.makeText(this,"你没有获得摄像头权限",Toast.LENGTH_SHORT).show();
            }
        }else if(requestCode == 0){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                openAlbum();
            }else {
                Toast.makeText(this,"你没有获得相册权限",Toast.LENGTH_SHORT).show();
            }
        }
    }
    //4.执行拍照
    private void doTake() {
        File imageTemp = new File(getExternalCacheDir(),"imageOut.jpeg");
        if(imageTemp.exists()){
            imageTemp.delete();
        }
        try {
            imageTemp.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(Build.VERSION.SDK_INT > 24){
            photoURI = FileProvider.getUriForFile(this, "com.drojian.demo.fileprovider", imageTemp);
        }else {
            photoURI = Uri.fromFile(imageTemp);
        }
        Intent intent = new Intent();
        intent.setAction("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
        startActivityForResult(intent,1);
    }
    //5.设置照片
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1){
            if(resultCode == RESULT_OK){
                try {
                    //处理照片
                    InputStream inputStream = getContentResolver().openInputStream(photoURI);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    mImageView.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        }else if(requestCode == 0){
            if(Build.VERSION.SDK_INT < 19){
                Uri uri = data.getData();
                String imagePath = getImagePath(uri,null);
                displayImage(imagePath);
            }else{
                handleImageOnApi19(data);
            }
        }
    }
    @TargetApi(19)
    private void handleImageOnApi19(Intent data) {
            String imagePath = null;
            Uri uri = data.getData();
            if(DocumentsContract.isDocumentUri(this,uri)){
                String documentId = DocumentsContract.getDocumentId(uri);
                if(TextUtils.equals(uri.getAuthority(),"com.android.providers.media.documents")){
                    String id = documentId.split(":")[1];
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                } else if (TextUtils.equals(uri.getAuthority(),"com.android.providers.downloads.documents")){
                    if(documentId != null && documentId.startsWith("msf:")){
                        resolveMSFContent(uri,documentId);
                        return;
                    }
                    Uri conteneUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                    imagePath = getImagePath(conteneUri,null);
                }
            }else if ("content".equalsIgnoreCase(uri.getScheme())){
                     imagePath = getImagePath(uri, null);
            }else if ("file".equalsIgnoreCase(uri.getScheme())){
                imagePath = uri.getPath();
            }
            displayImage(imagePath);
    }

    private void resolveMSFContent(Uri uri, String documentId) {
        File file = new File(getCacheDir(), "temp_file" + getContentResolver().getType(uri).split("/")[1]);
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            OutputStream outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int read;
            while((read = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,read);
            }
            outputStream.flush();
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            mImageView.setImageBitmap(bitmap);
            ImageUtil.imageToBase64(bitmap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    private String getImagePath(Uri uri,String selection){
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null, null);
        if(cursor != null){
            if(cursor.moveToFirst()){
                path =  cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    private void displayImage(String imagePath){
        if(imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            mImageView.setImageBitmap(bitmap);
        }
    }


    //2.权限判定
    private void choosePhoto() {
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED){
            // 打开相册
            openAlbum();
        }else{
            //申请权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},0);
        }

    }
    //3.接受权限申请结果上边的onRequestPermissionsResult
    //4.执行打开相册
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,0);
    }
    //5.接收上边的onActivityResult
}